package com.vmove.childtrain.db.dao;

import android.content.Context;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.misc.TransactionManager;
import com.vmove.childtrain.db.DatabaseHelper;
import com.vmove.childtrain.db.entity.Data;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Description: 训练记录数据dao
 */

public class DataDao {
    /**
     * 获取所有程序列表
     * select count(*) buzhou,step.stepName，bussinesId from step GROUP BY bussinId;
     */

    /**
     * 根据业务id查找所有步骤，并根据order字段排序
     * select * from step where bussinId=1001 ORDER BY `order`;
     */

    private Dao<Data, Integer> dataDaoOpe;
    private DatabaseHelper helper;

    @SuppressWarnings("unchecked")
    public DataDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            dataDaoOpe = helper.getDao(Data.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param id
     * @return
     */
    public Data get(int id) {
        Data data = null;
        try {
            data = dataDaoOpe.queryForId(id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return data;
    }

    public List<Data> getDatasByRecordId(int rid){
        try {
            return dataDaoOpe.queryForEq("recordId", rid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * @param id
     */
    public void deleteRecordById(int id) {
        String sql = "delete from tb_data where id = " + id;
        try {
            dataDaoOpe.queryRaw(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public int addRecord(Data record){
        try {
           return dataDaoOpe.createOrUpdate(record).getNumLinesChanged();
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 批量事务添加
     */
    public boolean addDatas(final List<Data> records) {
        boolean isSucc=false;
        try {
            isSucc = TransactionManager.callInTransaction(helper.getConnectionSource(),
                    new Callable<Boolean>()
                    {

                        @Override
                        public Boolean call() throws Exception
                        {
                            for (Data s:records) {
                                dataDaoOpe.createOrUpdate(s);
                            }
                            return true;
                        }
                    });
        } catch (SQLException e) {
            e.printStackTrace();
            return isSucc=false;
        }
        return isSucc;
    }

}
